package com.cy.cuiyang_admin.util;

import com.cy.cuiyang_admin.config.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redicache 工具类
 */
@SuppressWarnings("unchecked")
@Component
@Slf4j
public class RedisUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class);

    @SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }
    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }
    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 读缓存
     * @param key
     * @return
     */
    public Object getObject(String key, Class<?> clazz) {
        try {
            final byte[] keyBytes = key.getBytes("UTF-8");
            final byte[] result = (byte[]) redisTemplate.execute(new RedisCallback<byte[]>() {
                @Override
                public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.get(keyBytes);
                }
            });
            if (result != null && result.length > 0) {
                return JsonHelper.toObject(result, clazz);
            }
        } catch (Exception e) {
            LOGGER.info("d失败"+e.getMessage());
        }
        return null;
    }

    /**
     * 读缓存， 它兼容RedisTemplate的对象存储，
     *   如果发现是redisTemplate对象格式 （["com.ccc.model", {实际数据}]）
     *   它将解析出内部的实际数据
     * @param key
     * @return
     */
    public Object getSingleObject(String key, Class<?> clazz) {
        try {
            final byte[] keyBytes = key.getBytes("UTF-8");
            final byte[] result = (byte[]) redisTemplate.execute(new RedisCallback<byte[]>() {
                @Override
                public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.get(keyBytes);
                }
            });
            if (result != null && result.length > 0) {
                // ["com.ccc.model", {实际数据}]
                if (result[0] == '[' && result[1] == '"' && result[result.length - 1] == ']') {
                    String json = new String(result, 1, result.length - 2);
                    int pos = json.indexOf('{');
                    json = json.substring(pos);
                    return JsonHelper.toObject(json, clazz);
                } else {
                    return JsonHelper.toObject(result, clazz);
                }
            }
        } catch (Exception e) {
            LOGGER.error("失败"+e.getMessage());
        }
        return null;
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public String getString(final String key) {
        String result;
        ValueOperations<Serializable, String> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            LOGGER.error("失败"+e.getMessage());
        }
        return result;
    }
    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long seconds) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            LOGGER.error("失败"+e.getMessage());
        }
        return result;
    }

    /**
     * 写缓存,其过期时间单位为天
     * @param key
     * @param value
     * @param expireDay
     * @return
     */
    public boolean setObject(final String key, Object value, int expireDay) {
        try {
            final byte[] keyBytes = key.getBytes("UTF-8");
            final byte[] jsonBytes = JsonHelper.toJsonBytes(value);
            return (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {
                @Override
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.set(keyBytes, jsonBytes,
                            Expiration.seconds(expireDay * 3600 * 24),
                            RedisStringCommands.SetOption.UPSERT);
                }
            });
        } catch (Exception e) {
            LOGGER.error("失败"+e.getMessage());
        }
        return false;
    }

    /**
     * 写缓存，其过期时间单位为秒
     * @param key
     * @param value
     * @param seconds
     * @return
     */
    public boolean setObject(final String key, Object value, long seconds) {
        try {
            final byte[] keyBytes = key.getBytes("UTF-8");
            final byte[] jsonBytes = JsonHelper.toJsonBytes(value);
            return (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {
                @Override
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.set(keyBytes, jsonBytes,
                            Expiration.seconds(seconds),
                            RedisStringCommands.SetOption.UPSERT);
                }
            });
        } catch (Exception e) {
            LOGGER.error("失败"+e.getMessage());
        }
        return false;
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, int days) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, days, TimeUnit.DAYS);
            result = true;
        } catch (Exception e) {
            LOGGER.error("失败"+e.getMessage());
        }
        return result;
    }
}
